import React, { useEffect,useRef,useState } from 'react'
import { View,Text,Image, Canvas, CoverView } from '@tarojs/components'
import QRCode from '@/utils/qrcode.min.js'
import './index.less'
import Taro from '@tarojs/taro'

export default function wholeOrderDetail() {
  const [isShow, setisShow] = useState(false)
  const codeimg = useRef('')
  const [title, settitle] = useState({
    nickName: '',
    desc: '',
    imgUrl: '',
    storageKeyUrl: 'bodt_pic'
  })
  let statics = {
    placBgHead: {
      key: 'plac_bg_head',
      url: 'https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/plac_bg_head.png'
    },
    placBodyLetb: {
      key: 'plac_body_let_b',
      url: 'https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/plac_body_let_b.png'
    },
    placBodyLetf: {
      key: 'plac_body_let_f',
      url: 'https://taihu-finesdk.oss-cn-beijing.aliyuncs.com/fine-event/20240506/placard/plac_body_let_f.png'
    }
  }

  useEffect(()=>{
    init()
  },[])

  const init = async ()=> {
    const {router} = Taro.getCurrentInstance()
    setisShow(!isShow)
    Taro.showToast({
      title: '海报生成中……',
      icon: 'loading',
    })
    if (!router.params?.orderId) {
      Taro.showToast({
        title: '生成海报失败!',
        icon: 'warn',
        duration: 1500
      })
      setisShow(false)
      return;
    }
    try {
      let res = await Taro.$get(`/marketing/app/package/getPosterInfo`, {
        orderId: router.params?.orderId
      })
      if (res.code === '1') {
        const resObj = res.content
        let storageKeyUrl = title.storageKeyUrl + new Date().getTime()
        const obj = {
          nickName: resObj.userName,
          desc: '邀您参加' + resObj.relationObject.title + '影院观赛',
          bottomTitle: resObj.bottomTitle,
          bottomDesc: resObj.bottomDesc,
          applyTimeEnd: resObj.applyTimeEnd,
          address: resObj.address,
          validityPeriod: resObj.validityPeriod,
          imgUrl: resObj.relationObject.imgUrl,
          storageKeyUrl
        }
        settitle(obj)
        QRCode({
          width: 90,
          height: 90,
          canvasId: 'myQrcode',
          text: resObj.qrCode
        })
        // 使用Promise.all等待所有下载操作完成
        Promise.all([
          new Promise((resolve, reject) => {
            downLoadImg(statics.placBgHead.url, statics.placBgHead.key, (path) => {
              statics.plac_bg_head = path;
              resolve(path);
            });
          }),
          new Promise((resolve, reject) => {
            downLoadImg(statics.placBodyLetb.url, statics.placBodyLetb.key, (path) => {
              statics.plac_body_let_b = path;
              resolve(path);
            });
          }),
          new Promise((resolve, reject) => {
            downLoadImg(statics.placBodyLetf.url, statics.placBodyLetf.key, (path) => {
              statics.plac_body_let_f = path;
              resolve(path);
            });
          }),
          new Promise((resolve, reject) => {
            downLoadImg(resObj.relationObject.imgUrl, storageKeyUrl, (path) => {
              statics.dmImgUrl = path;
              resolve(path);
            });
          })
        ]).then(res=>{
          getCodeUrl(obj);
        })
      }
    } finally {
      Taro.hideToast();
    }
  }

  async function downLoadImg(netUrl, storageKeyUrl, callback) {
    await Taro.getImageInfo({
      src: netUrl,
      success: async function(res) {
        await Taro.setStorage({
          key: storageKeyUrl,
          data: res.path, 
        });
        callback && callback(res.path)
      },
      fail(info) {
        Taro.showToast({
          title: JSON.stringify(info),
          icon: 'loading',
        })
      }
    });
  }
  function getCodeUrl(title) {
    Taro.canvasToTempFilePath({
      canvasId:'myQrcode',
      width: 90,
      height: 90,
      success:res=>{
        getPath(Taro.getFileSystemManager().readFileSync(res.tempFilePath, 'base64'),title)
      }
    })
  }
  function getPath(code,title) {
    const fs = Taro.getFileSystemManager();
    var times = new Date().getTime();
    codeimg.current = Taro.env.USER_DATA_PATH + '/' + times + '.png';
    fs.writeFile({
      filePath: codeimg.current,
      data: code,
      encoding: 'base64',
      success: () => {
        drowCanvas(title)
      }
    });
  }
  function drowCanvas(title) {
    let system_info = Taro.getSystemInfoSync();
    let rpx = system_info.windowWidth / 388
    let rpxh = system_info.windowWidth / 400
    const ctx = Taro.createCanvasContext('placardCanvas')

    ctx.fillStyle = "#db3729";
    ctx.fillRect(0, 0, Taro.getSystemInfoSync().windowWidth, 1400 * rpxh)
    ctx.globalAlpha = 0.2; // 设置透明度为50%
    ctx.drawImage(statics.plac_bg_head, 0, 0, Taro.getSystemInfoSync().windowWidth, 280 * rpxh)
    fillRoundRect(ctx, 29 * rpx, 72 * rpxh, 330 * rpx, 53 * rpxh, 8 * rpx, 'rgba(255, 233, 191, 0.2)');
    ctx.fillStyle = "#FFDF6F";
    ctx.globalAlpha = 1; // 恢复默认透明度
    ctx.drawImage(statics.plac_body_let_b, 7 * rpx, 251 * rpxh, 376 * rpx, 333 * rpxh)
    ctx.drawImage(statics.dmImgUrl, 30 * rpx, 138 * rpx, 329 * rpx, 420 * rpxh )
    
    ctx.drawImage(statics.plac_body_let_f, 15 * rpx, 532 * rpxh, 358 * rpx, 133 * rpxh)

    ctx.setFillStyle('#ffffff')
    ctx.font = "12rpx PingFang SC";
    ctx.fillText('使用时间', 85 * rpx, 92 * rpxh, 200 * rpx);
    ctx.fillText('适用地点', 255 * rpx, 92 * rpxh, 200 * rpx);

    ctx.font = "bold 14px Arial";
    ctx.fillText('领取后' + title.validityPeriod + '天内', 65 * rpx, 115 * rpxh, 200 * rpx);
    ctx.fillText(title.address, 235 * rpx, 115 * rpxh, 200 * rpx);

    ctx.font = "bold 28rpx PingFang SC";
    ctx.fillText(title.nickName, 30 * rpx, 30 * rpxh);
    ctx.font = "16rpx PingFang SC";
    ctx.fillText(title.desc, 30 * rpx, 55 * rpxh, 300 * rpx);

    ctx.font = "bold 20rpx PingFang SC";
    ctx.fillText(title.bottomTitle, 124 * rpx, 590 * rpxh, 200 * rpx);
    ctx.font = "bold 14rpx PingFang SC";
    ctx.fillText(title.bottomDesc, 124 * rpx, 620 * rpxh, 200 * rpx);
    ctx.font = "400 12px PingFang SC";
    ctx.fillText('领取时间' + title.applyTimeEnd + '前可领', 124 * rpx, 647 * rpxh, 200 * rpx);
    ctx.drawImage(codeimg.current, 31 * rpx, 571 * rpxh, 80, 80 * rpxh)
    ctx.draw()
  }
  function drawRoundRectPath(cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线
    cxt.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线
    cxt.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI
    cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

    //上边线
    cxt.lineTo(width - radius, 0);

    //右上角圆弧
    cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

    //右边线
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  }
  function fillRoundRect(cxt, x, y, width, height, radius, fillColor) {
    //圆的直径必然要小于矩形的宽高
    if (2 * radius > width || 2 * radius > height) {
      return false;
    }

    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边
    drawRoundRectPath(cxt, width, height, radius);
    cxt.fillStyle = fillColor || "#000"; //若是给定了值就用给定的值否则给予默认值
    cxt.fill();
    cxt.restore();
  }

  function saveImage() {
    Taro.showToast({
      title: '截图保存中……',
      icon: 'loading',
    })
    setTimeout(() => {
      Taro.canvasToTempFilePath({
        canvasId: 'placardCanvas',
        fileType: 'png',
        quality: 1,
        success: (res) => {
          let tempFilePath = res.tempFilePath
          Taro.getSetting({
            success: (res) => {
              if (res.authSetting['scope.writePhotosAlbum']) {
                saveImageToPhotosAlbum(tempFilePath);
              } else {
                Taro.authorize({
                  scope:'scope.writePhotosAlbum',
                  success: () => {
                    // 授权成功，保存图片
                    saveImageToPhotosAlbum(tempFilePath);
                  },
                  fail: (err) => {
                    console.log(err);
                    Taro.showToast({
                      title: '授权失败，无法保存图片',
                      icon: 'error',
                      duration: 3000
                    });
                  }
                })
              }
            },
            fail: (err) => {
              console.log(err);
              Taro.showToast({
                title: '获取权限设置失败',
                icon: 'error',
                duration: 3000
              });
            }
          })
          
        },
        fail(res) {
          console.log('fail', res);
        }
      });
    }, 2000)
  }
  function saveImageToPhotosAlbum(imgUrl) {
    if (imgUrl) {
      Taro.saveImageToPhotosAlbum({
        filePath: imgUrl,
        success: (res) => {
          console.log(res);
          Taro.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 3000
          });
        },
        fail: (err) => {
          console.log(err);
          Taro.showToast({
            title: '保存失败',
            icon: 'error',
            duration: 3000
          });
        }
      });
    } else {
      Taro.showToast({
        title: '绘制中……',
        icon: 'loading',
        duration: 3000
      })
    }
  }

  function showOrder() {
    Taro.navigateTo({
      url: '/mineSubPack/wholeCinema/wholeCinemaOrder/index'
    })
  }

  return (
    <View class="placard-canvas">
      {isShow?<>
        <Canvas style='margin: 10px;position:absolute;z-index:-1000' className='item-img' canvas-id="myQrcode"></Canvas>
        <Canvas canvas-id="placardCanvas" id='pl_anvas'></Canvas>
      </>:null}
      <CoverView class="footer">
        <CoverView onClick={()=>{showOrder()}} style="border-radius: 32px; width: 336rpx; height: 80rpx; border: 1px solid #E6E8EA; font-size: 32rpx; font-weight: 700; display: flex; align-items: center; justify-content: center; margin-left: 24rpx;">
          <CoverView>查看订单</CoverView>
        </CoverView>
        <CoverView onClick={()=>{saveImage()}} style="border-radius: 32px; width: 336rpx; height: 80rpx; border: 1px solid #FF0D49; background-color: #FF0D49; color: #FFFFFF; font-size: 32rpx; font-weight: 700; display: flex; align-items: center; justify-content: center; margin-right: 24rpx;">
          <CoverView>保存海报</CoverView>
        </CoverView>
      </CoverView>
    </View>
  )
}
